package month1;

public class WorkSearch79_06 {
    public static void main(String[] args) {
        System.out.println(exist(new char[][]{{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}, "ABCCED"));
    }

    /**
     * 回溯搜索
     * @param board
     * @param word
     * @return
     */
    static boolean exist(char[][] board, String word) {
        for (int i = 0; i < board.length; ++i) {
            for (int j = 0; j < board[0].length; ++j) {
                if (word.charAt(0) == board[i][j] && traceback(board, i, j, word, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    static boolean traceback(char[][] board, int i, int j, String word, int k) {
        if (k == word.length()) {
            return true;
        }
        if (i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word.charAt(k)) {
            return false;
        }
        board[i][j] += 100;
        boolean ret = traceback(board, i + 1, j, word, k + 1) || traceback(board, i, j + 1, word, k + 1) || traceback(board, i - 1, j, word, k + 1) || traceback(board, i, j - 1, word, k + 1);
        board[i][j] -= 100;
        return ret;
    }
}

